<template>
    <div class="page-container">
        <div class="calendar-container">
            <el-calendar v-model:model-value="selectedDate">
                <template #date-cell="{ data }">
                    <div class="date-cell" :class="{'has-schedule': schedulesByDate[data.day]}">
                        <!-- 日期显示 -->
                        <p class="date-number">{{ data.day.split('-').slice(-1)[0] }}</p>
                    </div>
                </template>
            </el-calendar>
        </div>

        <!-- 日程卡片列表 -->
        <div class="schedule-card-grid">
            <div v-for="schedule in schedules" :key="schedule.id" class="card">
                <el-card>
                    <template #header>
                        <div class="card-header">
                            <h2>{{ schedule.title }}</h2>
                            <div class="card-meta">
                                <span>分类: {{ schedule.categoryName }}</span>
                                <span>提醒时间: {{ schedule.remindTime }}</span>
                                <span>重要程度: {{ schedule.typeName }}</span>
                                <span>状态:
                                    <span v-if="schedule.state === 0">未完成</span>
                                    <span v-else-if="schedule.state === 1">已完成</span>
                                </span>
                            </div>
                        </div>
                    </template>
                    <div class="card-content">
                        <!-- 显示日程内容 -->
                        <div v-html="schedule.content"></div>
                    </div>
                    <div class="card-actions">
                        <el-button
                            :type="schedule.state === 0 ? 'danger' : 'success'"
                            @click="updateState(schedule)"
                        ><!-- 动态切换按钮类型 -->
                            <span v-if="schedule.state === 0">任务未完成😨</span>
                            <span v-else>任务已完成🎉</span>
                        </el-button>
                        <el-button :icon="Edit" circle plain type="primary" @click="showDialog(schedule)"></el-button>
                        <el-button :icon="Delete" circle plain type="danger" @click="deleteSchedule(row)"></el-button>
                    </div>
                </el-card>
            </div>
        </div>

        <!-- 分页条 -->
        <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[6, 10, 20, 30]"
            layout="jumper, total, sizes, prev, pager, next"
            background
            :total="total"
            @size-change="onSizeChange"
            @current-change="onCurrentChange"
            style="margin-top: 20px; justify-content: flex-end"
        />
    </div>

    <ScheduleDrawer
        :visible="visibleDrawer"
        :title="drawerTitle"
        :categories="categories"
        :schedule-model="currentSchedule"
        @addSchedule="addSchedule"
        @updateSchedule="updateSchedule"
        @cancel="handleDrawerCancel"
    />
</template>

<script setup>
import {ref, onMounted, watch} from 'vue';
import {
    scheduleCategoryListService, scheduleDeleteService,
    scheduleListService,
    scheduleSearchByDateService,
    scheduleUpdateStateService
} from '@/api/schedule.js';
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit} from "@element-plus/icons-vue";
import ScheduleDrawer from "@/views/schedule/ScheduleDrawer.vue";

// 存储所有日程数据
const schedules = ref([
    {
        "id": 1,
        "title": "项目会议",
        "content": "内容",
        "state": 0,
        "emergencyDegree": 1,
        "categoryId": 2,
        "remindTime": "2023-09-03 11:55:30",
        "createTime": "2023-09-03 11:55:30",
        "updateTime": "2023-09-03 11:55:30"
    }
]);
// 按日期分组的日程数据
const schedulesByDate = ref({});
const selectedDate = ref(new Date)
watch(selectedDate, (newDate, oldValue) => {
    handleCellClick(newDate)
})

// 分页条数据模型
const pageNum = ref(1); // 当前页
const total = ref(0); // 总条数
const pageSize = ref(10); // 每页条数

// 当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size;
    refreshScheduleList();
};

// 当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num;
    refreshScheduleList();
};

// 刷新日程列表
const refreshScheduleList = async () => {
    await getScheduleCategoryList();
    await getScheduleList();
};

// 获取日程分类列表
const getScheduleCategoryList = async () => {
    try {
        let result = await scheduleCategoryListService();
        categories.value = result.data;
    } catch (error) {
        ElMessage.error('获取日程分类列表失败');
    }
};

//用户搜索时选中的发布状态
const state = ref('')

//用户搜索时选中的分类id
const categoryId = ref('')

// 用户搜索时选中的日程状态
const scheduleState = ref('')

// 用户搜索时选中的日程紧急程度
const emergencyDegree = ref('');

// 新增搜索关键字
const keyword = ref('')

// 日程类型数据模型，初始化数据
const scheduleTypes = ref([
    {id: 1, typeName: "重要紧急", color: "#f56c6c"},
    {id: 2, typeName: "重要不紧急", color: "#e6a23c"},
    {id: 3, typeName: "紧急不重要", color: "#5cb87a"},
    {id: 4, typeName: "不重要不紧急", color: "#909399"}
]);

//日程分类数据模型，添加更多分类
const categories = ref([
    {
        "id": 1,
        "categoryName": "工作",
        "categoryAlias": "work",
        "createTime": "2023-09-01 12:06:59",
        "updateTime": "2023-09-01 12:06:59"
    }
])

// 获取日程列表
const getScheduleList = async () => {
    try {
        let params = {
            pageNum: pageNum.value,
            pageSize: pageSize.value,
            categoryId: categoryId.value ? categoryId.value : null,
            state: state.value ? state.value : null,
            emergencyDegree: emergencyDegree.value ? emergencyDegree.value : null,
            keyword: keyword.value || null // 添加搜索关键字参数
        }
        let result = await scheduleListService(params);

        //渲染视图
        total.value = result.data.total;
        schedules.value = result.data.items;

        //处理数据，给数据模型扩展一个属性categoryName，分类名称
        for (let i = 0; i < schedules.value.length; i++) {
            let schedule = schedules.value[i];
            for (let j = 0; j < categories.value.length; j++) {
                if (schedule.categoryId === categories.value[j].id) {
                    schedule.categoryName = categories.value[j].categoryName;
                }
            }
            // 处理类型名称
            for (let k = 0; k < scheduleTypes.value.length; k++) {
                if (schedule.emergencyDegree === scheduleTypes.value[k].id) {
                    schedule.typeName = scheduleTypes.value[k].typeName;
                }
            }
        }
        // 按日期分组日程数据
        getSchedulesByDate();
    } catch (error) {
        ElMessage.error('获取全部日程列表失败')
        console.error('获取全部日程列表失败:', error);
    }
};

// 按日期分组日程数据
const getSchedulesByDate = (date) => {
    if (date) {
        return schedulesByDate.value[date] || [];
    }
    schedulesByDate.value = {};
    schedules.value.forEach(schedule => {
        const scheduleDate = schedule.remindTime.split('T')[0];
        if (!schedulesByDate.value[scheduleDate]) {
            schedulesByDate.value[scheduleDate] = [];
        }
        schedulesByDate.value[scheduleDate].push(schedule);
    });
    return schedulesByDate.value;
};


onMounted(async () => {
    await getScheduleCategoryList();
    await getScheduleList();
});

const handleCellClick = async (date) => {
    // 使用本地时间格式化为 YYYY-MM-DD
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const selectedDate = `${year}-${month}-${day}`;    // 调用按日期筛选日程的服务
    try {
        let params = {
            date: selectedDate,
            pageNum: pageNum.value,
            pageSize: pageSize.value
        }
        const result = await scheduleSearchByDateService(params);

        // 更新全局日程列表为当天数据
        total.value = result.data.total; // 更新总条数（若需要分页）
        schedules.value = result.data.items || []; // 直接渲染当天日程

        // 重新处理分类和类型名称
        handleScheduleData(schedules.value); // 新增数据处理函数

    } catch (error) {
        ElMessage.error('按日期筛选日程失败');
        console.error('按日期筛选日程失败:', error);
    }
};

// 统一处理日程数据（分类/类型名称）
const handleScheduleData = (list) => {
    list.forEach(schedule => {
        // 处理分类名称
        schedule.categoryName = categories.value.find(category => category.id === schedule.categoryId)?.categoryName || '未分类';
        // 处理类型名称
        schedule.typeName = scheduleTypes.value.find(type => type.id === schedule.emergencyDegree)?.typeName || '无类型';
    });
};

// 显示编辑弹窗
const showDialog = (row) => {
    drawerTitle.value = '编辑日程'
    currentSchedule.value = {
        ...row,
        id: row.id
    }
    visibleDrawer.value = true
};

// 新增状态管理
const visibleDrawer = ref(false)
const drawerTitle = ref('添加日程')
const currentSchedule = ref({
    title: '',
    categoryId: '',
    content: '',
    state: '',
    emergencyDegree: '',
    id: null
})

// 添加日程
const addSchedule = (result) => {
    ElMessage.success(result.msg || '添加成功')
    window.location.reload()
}

// 更新日程
const updateSchedule = (result) => {
    ElMessage.success(result.msg || '修改成功')
    window.location.reload()
}

const handleDrawerCancel = () => {
    ElMessageBox.confirm('确定要放弃修改吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        visibleDrawer.value = false
        currentSchedule.value = {
            title: '',
            categoryId: '',
            content: '',
            state: '',
            emergencyDegree: '',
            id: null
        }
    })
}

//更新日程状态信息，使得日程变成“已完成”
const updateState = async (schedule) => {
    try {
        const newState = schedule.state === 0 ? 1 : 0;
        const newSchedule = {...schedule, state: newState };
        await scheduleUpdateStateService(newSchedule);
        schedule.state = newState;
        ElMessage.success('日程状态更新成功');
    } catch (error) {
        ElMessage.error('日程状态更新失败');
    }
};

const deleteSchedule = (row) => {
    // 提示用户，确认框
    ElMessageBox.confirm(
        '你确认要删除该日程信息吗？',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            try {
                // 调用接口
                let result = await scheduleDeleteService(row.id);
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                // 刷新列表
                await scheduleList();
            } catch (error) {
                ElMessage({
                    type: 'error',
                    message: '删除失败，请稍后重试',
                })
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
</script>

<style lang="scss" scoped>
@use "@/assets/scss/card-style";

.calendar-container {
    margin: 0 auto;
    width: 80%;
    max-width: 800px;
    padding: 20px;
}

.schedule-card-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    column-gap: 0; /* 列与列之间的间距 */
    row-gap: 0; /* 行与行之间的间距 */
    width: 88%;
    margin: 0 auto;
}

.card-meta {
    display: flex;
    flex-wrap: wrap;
    padding: 0;
}

.card-meta > div {
    width: 50%;
    box-sizing: border-box;
}

.date-cell {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%; /* 确保高度覆盖整个格子 */
    width: 100%; /* 确保宽度覆盖整个格子 */
}

.date-cell.has-schedule {
    background-color: rgba(64, 158, 255, 0.3); /* 使用透明度为0.3的蓝色 */
    border-radius: 5px; /* 圆角效果 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 柔和的阴影效果 */
}
</style>
